<template>
  <div class="travel-list-container">
    <!-- <h1>报销单列表</h1> -->
    <el-row>
      <!-- 查询表单 -->
      <el-col :span="16">
        <el-form :inline="true" :model="queryForm" class="demo-form-inline">
          <el-form-item label="报销单号">
            <el-input 
              v-model="queryForm.travelId" 
              placeholder="请输入单号"
              style="width: 180px;" 
            ></el-input>
          </el-form-item>

          <!-- 日期选择 -->
          <el-form-item label="报销日期">
            <el-date-picker  
              v-model="queryForm.startTime" 
              type="date"
              placeholder="起始日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 160px; margin-right: 10px;" 
            ></el-date-picker >
            <span style="margin: 0 5px;">至</span>
            <el-date-picker 
              v-model="queryForm.endTime" 
              type="date"
              placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 160px; margin-left: 10px;" 
            ></el-date-picker>
          </el-form-item>

          <!-- 查询按钮 -->
          <el-form-item>
            <el-button type="primary" @click="getTableData">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 操作按钮 -->
      <el-col :span="8" style="text-align: right;">
        <el-button-group>
          <el-button type="primary" @click="openDialog">新增</el-button>
          <el-button type="primary" @click="getOne">编辑</el-button>
          <el-button type="primary" @click="delTravel">删除</el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row>
      <el-col>
        <el-table
          ref="multipleTable"
          :data="travelList"
          tooltip-effect="dark"
          style="width: 100%;"
          height="400px"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
          <el-table-column label="报销单号" min-width="170" align="center">
            <template slot-scope="scope">{{ scope.row.travelId }}</template>
          </el-table-column>
          <el-table-column label="员工工号" min-width="80" align="right">
            <template slot-scope="scope">{{ scope.row.empno }}</template>
          </el-table-column>
          <el-table-column label="起始日期" min-width="100" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.startTime) }}</template>
          </el-table-column>
          <el-table-column label="结束日期" min-width="100" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.endTime) }}</template>
          </el-table-column>
          <el-table-column label="出差天数" min-width="80" align="right">
            <template slot-scope="scope">{{ scope.row.days }}</template>
          </el-table-column>
          <el-table-column label="出差事由" min-width="100" align="center">
            <template slot-scope="scope">{{ scope.row.reason }}</template>
          </el-table-column>
          <el-table-column label="报销金额" min-width="100" align="right">
            <template slot-scope="scope">{{ scope.row.money }}</template>
          </el-table-column>
          <el-table-column label="报销时间" min-width="100" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.reimbursedTime) }}</template>
          </el-table-column>
          <el-table-column label="审批状态" min-width="160" align="center">
            <template slot-scope="scope">{{ getApprovalName(scope.row.approval) }}</template>
          </el-table-column>
          <el-table-column label="操作" min-width="80" align="center">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="handleShowApprovalFlow(scope.row)"
                class="flow-btn"
              >
                流程图
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination 
          background 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 8, 10]"
          :page-size="queryForm.limit"
          layout="prev, pager, next, total, sizes, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 弹出窗体 -->
    <travel-info :isShow="visible" :travelInfo="travelForm" @closeDialog="visible = false" @travelSave="tableLoad" @setTravelInfo="handleSetTravelInfo"></travel-info>
    <!-- 流程图弹窗：添加travel-id传递当前报销单ID，绑定关闭事件 -->
    <flowchart 
      :isShow="approvalDialogVisible" 
      :travelId="currentTravelId" 
      :currentStep="currentStep"
      ref="flowchart"
      @close="approvalDialogVisible = false" 
    ></flowchart>
  </div>
</template>

<script>
import TravelInfo from '@/components/TravelInfo.vue';
import Flowchart from '@/components/Flowchart.vue';

export default {
  name: 'TravelList',
  components: {
    TravelInfo,
    Flowchart
  },
  data() {
    return {
      travelList: [],
      checkedTravelList: [],
      queryForm: {
        travelId: '',
        startTime: '',
        endTime: '',
        page: 1,
        limit: 5,
        empno: localStorage.getItem('empno'),
      },
      currentTravelId: '', 
      currentStep: 0,
      total: 0, 
      visible: false, 
      approvalDialogVisible: false, 
      travelForm: {} 
      ,approvalList: []
    };
  },
  methods: {
    formatDate(date) {
      if (!date) return '未知';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleSelectionChange(val) {
      this.checkedTravelList = val;
    },
    getTableData() {
      this.$http.post('/travelList', this.queryForm).then(res => {
        this.travelList = res.data.records;
        this.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      this.queryForm.limit = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      this.getTableData();
    },

    // 处理子组件的重置通知
  handleSetTravelInfo(val) {
    this.getTableData();
    this.travelForm = val; 
  },

    //新增
    openDialog() {
      this.travelForm = {};
      this.visible = true;
    },
    tableLoad(msg) {
      if (msg === true) {
        this.visible = false;
        this.$message.success("保存成功");
        this.getTableData();
      }
    },

    //修改
    async getOne() {
      if (this.checkedTravelList.length === 0) {
        this.$message.warning("请选择要修改的报销单信息");
        return;
      }
      if (this.checkedTravelList.length > 1) {
        this.$message.warning("请选择一条数据进行修改");
        return;
      }

      let selected = this.checkedTravelList[0];
      let travelId = selected.travelId;

      
    this.$http.get('/getTravelById?travelId=' + travelId).then(res => {
      let travelBaseInfo = res.data;
      if (!travelBaseInfo) {
        this.$message.error("未找到差旅信息");
        return;
      }
      // 获取车票信息
      this.$http.get('/getTicketsByTravelId?travelId=' + travelId).then(res => {
        let tickets = Array.isArray(res.data) ? res.data : [];
        let validTickets = tickets.map(ticket => ({
          ...ticket,
          ticketId: ticket.ticketId
        }));
        this.travelForm = { ...travelBaseInfo, tickets: validTickets };
        this.visible = true;
      }).catch(err => {
        console.warn("获取车票信息失败:", err);
      });
    });
    },

    delTravel() {
      if (this.checkedTravelList.length === 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }
      this.$confirm('确定要删除选中的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let travelIds = this.checkedTravelList.map(item => item.travelId);
        this.$http.post('/deleteTravel', { travelIds : travelIds }).then(res => {
          if (res.data.code == 200) {
            this.$message.success("删除成功");
            this.getTableData();
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getApprovalList() {
      this.$http.get('/getApproval').then(res => {
        this.approvalList = res.data
      });
    },
  // 根据交通工具 ID 获取名称
    getApprovalName(value) {
      const map = {
        0: '未提交',
        1: '部门经理审核',
        2: '总经理审核',
        3: '已完成'
      }
      return map[value] || '未知状态';
    },

    // 获取审批数据的方法
    getApproval(travelId) { 
      let approval = this.$http.get('/getApprovalByTravelId?travelId=' + travelId
      ).then(res => {
          if (res.data !== null && res.data !== undefined) {
             this.currentStep = res.data; 
            return res.data;
          } else {
            this.$message.warning('未查询到审批数据');
            return null;
          }
        })
        .catch(() => {
          this.$message.error('获取审批数据失败');
          return null;
        });
      return approval;
    },
    
    // 打开流程图弹窗
    async handleShowApprovalFlow(row) {
      this.currentTravelId = row.travelId; // 设置当前报销单ID
      // 先获取审批数据，再显示弹窗
      const approval = await this.getApproval(row.travelId);
      if (approval !== null || approval !== undefined) {
        this.approvalDialogVisible = true;
      }
    }
  },
  created() {
    this.getTableData();
    this.getApprovalList(); // 获取审批状态列表
  }
};
</script>

<style scoped>
.travel-list-container {
  max-width: 1200px;
  margin: 0 auto;
}

.el-row {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 10px;
}

.el-button-group {
  display: flex;
  justify-content: flex-end;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
